package com.ruoyi.forum.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.forum.domain.ForumStudent;
import com.ruoyi.forum.domain.vo.ForumRegisterVo;
import com.ruoyi.forum.domain.vo.UpdatePassword;
import com.ruoyi.forum.service.IForumLoginService;
import com.ruoyi.forum.service.IForumStudentService;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysLogininforService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * 论坛登录管理（登录，修改密码，注册）
 */
@Api("用户信息管理")
@RestController
@RequestMapping("/forum")
public class ForumLoginController extends BaseController {

//    @PostMapping("/login")
//    @ApiOperation("论坛前台登录接口")
//    public boolean login(Object obj) {
//        return super.equals(obj);
//    }

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private IForumLoginService forumLoginService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IForumStudentService forumStudentService;

    @Autowired
    private RedisCache redisCache;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @Anonymous
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        SysUser user = userService.selectUserByUserName(loginBody.getUsername());
        if(user==null){
            return error("用户不存在/密码错误");
        }
        List<Long> longs = roleService.selectRoleListByUserId(user.getUserId());
        boolean isStudent = false;
        for(long roleid:longs){
            if(roleid == 100L){
                isStudent = true;
            }
        }
        if(!isStudent){
            return error("登录失败，该'" + loginBody.getUsername() + "'账号不存在");
        }
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 修改密码方法
     *
     */
    @PostMapping("/updatePassword")
    @Anonymous
    public AjaxResult updatePassword(@Valid @RequestBody UpdatePassword updatePassword)
    {
        Object cacheObject = redisCache.getCacheObject(updatePassword.getEmail());
        if(cacheObject!=null){
           String code = (String) cacheObject;
           if(!code.equals(updatePassword.getCode())){
               return popup("修改密码失败，邮箱验证码不正确");
           }
        }else {
            return popup("修改密码失败，邮箱验证码已失效。提示：验证码只有2分钟时效。");
        }
        //根据学生信息构建系统用户对象
        SysUser user = new SysUser();
        user.setEmail(updatePassword.getEmail());

        if (StringUtils.isEmpty(user.getEmail()) && userService.checkEmailUnique(user))
        {
            return error("修改密码失败，邮箱账号'" + user.getUserName() + "'不存在");
        }
        updatePassword.setPassword(SecurityUtils.encryptPassword(updatePassword.getPassword()));
        return toAjax(forumLoginService.updatePassword(updatePassword));
    }


    /**
     * 注册方法
     *
     */
    @PostMapping("/register")
    @Anonymous
    public AjaxResult register(@RequestBody ForumRegisterVo forumRegisterVo)
    {
        Object cacheObject = redisCache.getCacheObject(forumRegisterVo.getEmail());
        if(cacheObject!=null){
            String code = (String) cacheObject;
            if(!code.equals(forumRegisterVo.getCode())){
                return popup("学生注册失败，邮箱验证码不正确");
            }
        }else {
            return popup("学生注册失败，邮箱验证码已失效。提示：验证码只有2分钟时效。");
        }
        ForumStudent forumStudent = new ForumStudent();
        forumStudent.setStudentName(forumRegisterVo.getStudentName());
        forumStudent.setPassword(forumRegisterVo.getPassword());
        forumStudent.setNickName(forumRegisterVo.getNickName());
        forumStudent.setPhonenumber(forumRegisterVo.getPhonenumber());
        forumStudent.setSex(forumRegisterVo.getSex());
        forumStudent.setGrade(forumRegisterVo.getGrade());
        forumStudent.setSchoolId(forumRegisterVo.getSchoolId());
        forumStudent.setCollegeId(forumRegisterVo.getCollegeId());
        forumStudent.setSpecialtyId(forumRegisterVo.getSpecialtyId());
        forumStudent.setEmail(forumRegisterVo.getEmail());
        //根据学生信息构建系统用户对象
        SysUser user = new SysUser();
        user.setUserId(forumStudent.getStudentId());
        user.setUserName(forumStudent.getStudentName());
        user.setNickName(forumStudent.getNickName());
        user.setEmail(forumStudent.getEmail());
        user.setPhonenumber(forumStudent.getPhonenumber());
        user.setSex(forumStudent.getSex());
        user.setAvatar(forumStudent.getAvatar());
        user.setStatus(forumStudent.getStatus());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        forumStudent.setDeptId(200l);
        forumStudent.setCreateBy("admin");
        //设置（加密后的密码）
        forumStudent.setPassword(SecurityUtils.encryptPassword(forumStudent.getPassword()));
        return toAjax(forumStudentService.insertForumStudent(forumStudent));
    }



}
